/*
 * @Author: TT-hzy 
 * @Date: 2024-07-03 11:34:16
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-07-05 19:33:44
 * @Description: 
 */

import { Service } from "egg";


class ActionToken extends Service {

  async createToken(info: any) {
    const {
      ctx,
      app
    } = this;
    const token = ctx.app.jwt.sign({
      ...info
    }, app.config.jwt.secret, {
      expiresIn: '30d',// '1d'、'24h'、60，其中数值单位为秒
    });

    return token;
  }

  async getTokenInfo() {
    const {
      ctx,
      app
    } = this;
    const token = this.getHeaderToken();
    console.debug(ctx.app.jwt.decode(token));
    if (token === "") {
      return null;
    }
    var tokenInfo = ctx.app.jwt.verify(token, app.config.jwt.secret, {}) as any;
    if (typeof tokenInfo == 'string') {
      console.debug("tokenInfo is string");
    } else {
      console.debug("tokenInfo is object");
    }
    const info = tokenInfo;
    console.debug("tokenInfo:");
    console.debug(info);

    return info;
  }

  getHeaderToken() {
    const {
      ctx,
    } = this;
    const token = ctx.headers.authorization ? ctx.headers.authorization.split(' ')[1] : '';
    return token;
  }
}

export default ActionToken;